import os
from functools import wraps

import flask
from flask_restful import Api
from flask_mongoengine import MongoEngine

from app.resources.deployment import Deployment
from app.resources.image import Image
from app.resources.service import Service
from app.resources.instance import Instance
from app.resources.helpers import result_error

from config import config_object

gateway_host = os.environ.get('GATEWAY_HOST')
# check whether the request is from the same k8s namespace
http_host = 'pydeploy:5000'


def check_forwarded_host(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        env = flask.request.environ
        if env.get('HTTP_X_FORWARDED_HOST') == gateway_host \
                or env.get('REMOTE_ADDR') == '127.0.0.1' \
                or env.get('HTTP_HOST') == http_host:
            return func(*args, **kwargs)
        return result_error('400', None)

    return wrapper


app = flask.Flask(__name__)

app.config.from_object(config_object)
# connect to mongo
db = MongoEngine(app)

# if we want cors, use `cors.crossdomain(origin='*')`
api = Api(app, decorators=[check_forwarded_host])

api.add_resource(Deployment, '/deployment', '/deployment/<suffix>')
api.add_resource(Image, '/image')
api.add_resource(Service, '/service', '/service/<suffix>')
api.add_resource(Instance, '/instance')

# execute sequentially from the start of this file
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
